package com.wy.demo.utils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import org.apache.log4j.Logger;
public class FileUtils {
    private static final Logger logger = Logger.getLogger(FileUtils.class);

    /**
     * Rename a local file (always overwrite if target exists)
     *
     * @param oldFilePath original file path
     * @param newFilePath new file path
     * @return true if success, false otherwise
     */
    public static boolean renameFile(String oldFilePath, String newFilePath) {
        Path source = Paths.get(oldFilePath);
        Path target = Paths.get(newFilePath);
        try {
            if (!Files.exists(source)) {
                logger.error("Source file does not exist: " + oldFilePath);
                return false;
            }

            // ensure parent directory exists
            if (target.getParent() != null && !Files.exists(target.getParent())) {
                Files.createDirectories(target.getParent());
            }

            // overwrite target if exists
            Files.move(source, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
            return true;
        } catch (IOException e) {
            logger.error("Failed to rename file: " + oldFilePath + " -> " + newFilePath, e);
            return false;
        }
    }

    /**
     * 创建本地目录（如果不存在）
     */
    public static void createLocalDirectoryIfNotExists(String localDir) {
        Path path = Paths.get(localDir);
        if (!Files.exists(path)) {
            try {
                Files.createDirectories(path);
            } catch (IOException e) {
                logger.error("created folder error");
                throw new RuntimeException(e);
            }
            logger.info("create dir: " + localDir);
        }
    }

    /**
     * 清理未完成的临时文件 ,后缀为fileSuffix
     */
    public static void cleanupTempFiles(String localDir, String fileSuffix) {
        File dir = new File(localDir);

        if (!dir.exists() || !dir.isDirectory()) {
            throw new IllegalArgumentException("Provided path is not a valid directory: " + localDir);
        }

        File[] files = dir.listFiles((d, name) -> name.endsWith(fileSuffix));
        if (files == null) {
            throw new RuntimeException("Failed to list files in directory: " + localDir);
        }

        for (File file : files) {
            if (!file.delete()) {
                logger.error("delete file error: " + file.getAbsolutePath());
                throw new RuntimeException("Failed to delete file: " + file.getAbsolutePath());
            }else{
                logger.info("delete previous temp file,-->"+file.getAbsolutePath());
            }
        }
    }
    public static void deleteFile(String filePath){
        if (filePath != null) {
            File xmlFile = new File(filePath);
            if (xmlFile.exists()) {
                if (xmlFile.delete()) {
                    logger.debug("The file was deleted: " + filePath);
                } else {
                    logger.error("deleting files fail: " + filePath);
                }
            }
        }
    }
    public static void deleteFailFile(String localXmlPath,String localZipPath,String tempXmlPath,String tempZipPath){
        deleteFile(localXmlPath);
        deleteFile(localZipPath);
        deleteFile(tempXmlPath);
        deleteFile(tempZipPath);
    }
}
